package com.sky.controller.admin;

import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Author 2230823078_淡嘉浩
 * @Date 2025/3/7 下午10:13
 * Please don't copy!
 */
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;


    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传:{}",file);
        String filePath = null;
        // 得到dir - 比如我们的需求是根据当前的日期，来存放我们的文件比如今天 2022-12-12
        // java 基础我们讲解日期-SimpleDateFormat
        String dir = new SimpleDateFormat("yyyy/MM/dd").format(new Date());

        // 获取原始文件名
        try {
            String fileName = file.getOriginalFilename();
            //截取后缀
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            // 生成随机文件名
            String objectName = UUID.randomUUID().toString() + suffix;
            filePath = aliOssUtil.upload(file.getBytes(), objectName, dir);

        } catch (IOException e) {
            log.info("文件上传失败");
            return Result.error("文件上传失败");
        }
        return Result.success(filePath);
    }
}
